﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioManager : MonoBehaviour {

    private const int maxCountOfAudio = 10;
    public static AudioManager Instance = null;
    private Dictionary<string, AudioClip> AudioClipDictionary = new Dictionary<string, AudioClip>();
    //private Dictionary<string ,GameObject> 
    private const string ResourcePath = "Sounds/";
    private GameObject workGo;
    private GameObject idleGo;
    protected float BgmVal = 0;
    protected float GameVal = 0;

    // 背景音乐源
    private AudioSource AdBgm;

    void Awake()
    {
        if(Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            if(Instance != this)
            {
                Destroy(this.gameObject);
            }
        }
        this.BgmVal = PlayerPrefs.GetFloat("shezhi_yinyue", 1);
        this.GameVal = PlayerPrefs.GetFloat("shezhi_yinxiao", 1);
        // 创建背景音乐源
        GameObject BgmGo = new GameObject("BgmGo");
        BgmGo.transform.parent = this.transform;
        BgmGo.AddComponent<AudioSource>();
        this.AdBgm = BgmGo.GetComponent<AudioSource>();
        this.AdBgm.pitch = 1f;
        workGo = new GameObject("work");
        idleGo = new GameObject("idle");
        workGo.transform.SetParent(transform);
        idleGo.transform.SetParent(transform);
        idleGo.SetActive(false);

    }

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    /// <summary>
    /// 播放背景音乐
    /// </summary>
    public void PlayBgm(string audioname, float volume = 1)
    {
        if (!gameObject.activeSelf)
        {
            return;
        }
        AudioClip audioClip = null;
        if (this.AudioClipDictionary.ContainsKey(audioname))
        {
            this.AudioClipDictionary.TryGetValue(audioname, out audioClip);
        }
        else
        {
            audioClip = Resources.Load(ResourcePath + audioname) as AudioClip;
            if (audioClip == null)
            {
                return;
            }
            this.AudioClipDictionary.Add(audioname, audioClip);
        }
        this.AdBgm.volume = volume*this.BgmVal;
        this.AdBgm.clip = audioClip;
        this.AdBgm.loop = true;
        this.AdBgm.Play();
    }

    /// <summary>
    /// 播放音效
    /// </summary>
    /// <param name="audioname"></param>
    /// <param name="volume"></param>
    public void PlaySound(string audioname, float volume = 1)
    {
        if(!gameObject.activeSelf)
        {
            return;
        }
        volume *= this.GameVal;
        AudioClip audioClip = null;
        if(this.AudioClipDictionary.ContainsKey(audioname))
        {
            this.AudioClipDictionary.TryGetValue(audioname, out audioClip);
        }
        else
        {
            audioClip = Resources.Load(ResourcePath + audioname) as AudioClip;
            if(audioClip == null)
            {
                return;
            }
            this.AudioClipDictionary.Add(audioname, audioClip);
        }
        // 查找当前是否有同名的gameobject用于播放
        Transform tran = idleGo.transform.Find(audioname);
        if ( tran == null)
        {
           tran = new GameObject(audioname == null ? "SoundClip" : audioname).transform;
           tran.gameObject.AddComponent<AudioSource>();
        }
        tran.parent = this.workGo.transform;
        AudioSource source = tran.GetComponent<AudioSource>();
        source.pitch = 1f;
        source.volume = volume;
        source.clip = audioClip;
        StartCoroutine(this.PlayClipEndDestroy(tran));
        source.Play();
    }

    /// <summary>
    /// 音效播放完毕后删除
    /// </summary>
    /// <returns></returns>
    private IEnumerator PlayClipEndDestroy(Transform tran)
    {
        if(tran)
        {
            float len = tran.GetComponent<AudioSource>().clip.length * Time.timeScale;
            yield return new WaitForSeconds(len * Time.timeScale);
            tran.SetParent(this.idleGo.transform, false);
            if (this.idleGo.transform.childCount > maxCountOfAudio)
            {
                for (int i = 0; i < maxCountOfAudio / 2; ++i)
                {
                    Destroy(this.idleGo.transform.GetChild(i).gameObject);

                }
            }
        }
        yield break;
    }

    /// <summary>
    /// 设置音乐音量
    /// </summary>
    public void BGMSetVolume(float volume)
    {
        float baseVal = this.AdBgm.volume / this.BgmVal;
        this.BgmVal = volume;
        this.AdBgm.volume = baseVal*this.BgmVal;
    }

    /// <summary>
    /// 返回背景音乐音量
    /// </summary>
    /// <returns></returns>
    public float GetBGMVolume()
    {
        return this.AdBgm.volume / this.BgmVal;
    }

    /// <summary>
    /// 设置音效音量
    /// </summary>
    public void SetGameVolume(float volume)
    {
        this.GameVal = volume;
    }

    /// <summary>
    /// 返回音效音量
    /// </summary>
    public float GetGameVolume()
    {
        return this.GameVal;
    }

    /// <summary>
    /// 暂停所有音效音乐
    /// </summary>
    public void SoundAllPause()
    {
        AudioSource[] allsource = FindObjectsOfType<AudioSource>();
        if (allsource != null && allsource.Length > 0)
        {
            for (int i = 0; i < allsource.Length; i++)
            {
                allsource[i].Pause();
            }
        }
    }

    public void SoundAllResume()
    {
        AudioSource[] allsource = FindObjectsOfType<AudioSource>();
        if (allsource != null && allsource.Length > 0)
        {
            for (int i = 0; i < allsource.Length; i++)
            {
                allsource[i].Play();
            }
        }
    }

    public void SwitchMusic(bool music)
    {
        this.gameObject.SetActive(music);
    }
}
